using CfgTable;
using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.USDK;
using NetProtocol.Client;
using System;
using static NetProtocol.Client.CNetLoadPlayer;

namespace IQIGame.Onigao.GamePlay
{
    public class LoadPlayerModule : Singleton<LoadPlayerModule>, CNetLoadPlayer
    {
        private LoadPlayerModule() { }

        public static CNetLoadPlayer NetCore => Instance;


        /// <summary>
        /// 重写网络接口 自定义实现加载玩家信息
        /// </summary>
    	public UniTask<LoadPlayerResultData> CS_loadPlayer()
        {
            LogGame.Log("网络协议调用重写示例: before CS_loadPlayer");
            return NetCore._CS_loadPlayer();
        }

        public void SC_loadPlayerResult(ISession session, ref LoadPlayerResultData data)
        {
            LogGame.Log("网络协议调用返回重写示例: after CS_loadPlayer");
            //这里不能处理Result, 以免业务调用方困惑哪些Result字段由module处理 哪些由自己处理
            //这里可以处理的逻辑
            //1:记录日志/埋点
            //2:与Result无关的事件广播和内部逻辑处理
            NetCore._SC_loadPlayerResult(session, ref data);
        }


        /// <summary>
        /// 向服务器请求角色数据
        /// </summary>
        public async UniTaskVoid RequestRoleList()
        {
            var result = await NetCore.CS_getRoleList();
            if (result.IsSuccess)
            {
                if (result.roleList == null || result.roleList.Count == 0)
                {
                    ManagerCenter.UI.ShowWindow<UIRoleCreate>();
                }
                else
                {
                    ChooseRoleAsync(result.roleList[0].pid).Forget();
                }
            }
            else
            {
                LogGame.LogError($"SC_getRoleListResult error code = {result.code}");
            }
        }

        /// <summary>
        /// 创建游戏角色
        /// </summary>
        public async UniTaskVoid CreateRoleAsync(EM_GameRoleSex roleSex, string rndName)
        {
            var cfgOne = this.GetRoleInfo(roleSex);
            var createRoleResult = await NetCore.CS_createRole(cfgOne.Id, rndName);

            if (createRoleResult.IsSuccess)
            {
                if (ManagerCenter.ProjectSetting.IsSDKMode())
                {
                    IQIUSDK.Instance.createNewRole(SDKModule.Instance.GetNewRoleInfo(createRoleResult.role));
                }
                ChooseRoleAsync(createRoleResult.role.pid).Forget();
            }
            else
            {
                LogGame.LogError($"Player_CreateRoleResult error code = {createRoleResult.code}");
            }
        }

        private async UniTaskVoid ChooseRoleAsync(long pid)
        {
            var result = await NetCore.CS_chooseRole(pid);
            if (result.IsSuccess)
            {
                var player_LoadPlayerResult = await NetCore.CS_loadPlayer();
                if (player_LoadPlayerResult.IsSuccess)
                {
                    LogGame.Log($"CS_loadPlayer Success");
                    GameDataCenter.Init(player_LoadPlayerResult.player);
                    if (ManagerCenter.ProjectSetting.IsSDKMode())
                    {
                        IQIUSDK.Instance.enterGame(SDKModule.Instance.GetRoleInfo());
                    }
                    ProcedureFSM.Instance.ChangeState<ProcedureGame>();
                }
                else if (player_LoadPlayerResult.IsFail)
                {
                    LogGame.LogError($"Player_LoadPlayerResult error code = {player_LoadPlayerResult.code}");
                }
                else if (player_LoadPlayerResult.IsCanceled)
                {
                    LogGame.LogWarning($"Player_LoadPlayerResult is Canceled");
                }
            }
            else
            {
                LogGame.LogError($"Player_ChooseRoleResult error code = {result.code}");
            }
        }

        /// <summary>
        /// 随机角色配置数据
        /// </summary>
        public CfgRole GetRoleInfo(EM_GameRoleSex roleSex)
        {
            int id = APITableConfig.GetRoleCfgId(roleSex);
            return TableCenter.role.Get(id);
        }

        /// <summary>
        /// 随机角色名字
        /// </summary>
        public string GetRandRoleName()
        {
            var list = TableCenter.roleRandomName.DataList;
            var cnt = list.Count;
            if (cnt > 0)
            {
                int n1 = UnityEngine.Random.Range(0, cnt);
                int n2 = UnityEngine.Random.Range(0, cnt);
                int n3 = UnityEngine.Random.Range(0, cnt);
                var cfg1 = list[n1];
                var cfg2 = list[n2];
                var cfg3 = list[n3];
                return string.Concat(cfg1.Name1, cfg2.Name2, cfg3.Name3);
            }
            return "RoleRnd_" + DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString();
        }

        ISession CNetLoadPlayer.GetSession()
        {
            return GameServerModule.Instance.CurrSession;
        }
    }
}
